<template>
   <div class="login-page">
      <el-card class="box-card">
         <div slot="header" class="clearfix">
            <!-- <span class="login-title">电气与信息工程学院教务评分系统</span> -->
         </div>
         <div class="login-form">
            <!-- 登陆表单 -->
            <el-form :model="user" :rules="loginRules" v-if="!isRegister">
               <el-form-item prop="username">
                  <el-input type="text" v-model="user.username" auto-complete="off" placeholder="请输入用户名">
                     <template slot="prepend"><i style="font-size:20px" class="el-icon-s-custom"></i></template>
                  </el-input>
               </el-form-item>

               <el-form-item prop="password">
                  <el-input type="password" v-model="user.password" auto-complete="off" placeholder="请输入密码">
                     <template slot="prepend"><i style="font-size:20px" class="el-icon-key"></i></template>
                  </el-input>
               </el-form-item>
               <template slot="prepend"><i style="font-size:20px" class="el-icon-s-check"></i></template>
               <el-form-item prop="rolename">
                  <el-select v-model="user.rolename" placeholder="请选择角色" auto-complete="off" class="sel">
                     <el-option label="学生" value="学生"></el-option>
                     <el-option label="教师" value="教师"></el-option>
                     <el-option label="管理员" value="管理员"></el-option>
                  </el-select>

               </el-form-item>
               <el-form-item>
                  <el-button style="width:100%;" type="primary" @click="handleLogin">登录</el-button>
               </el-form-item>
               <el-form-item class="flex">
                  <el-link type="info" :underline="false" @click="RegisterchangeMsg(), clearuser()">
                     注册 →
                  </el-link>
               </el-form-item>
            </el-form>

            <!-- 注册表单 -->
            <el-form :model="user" :rules="loginRules" v-if="isRegister">
               <el-form-item prop="username">
                  <el-input type="text" v-model="user.username" auto-complete="off" placeholder="请输入用户名">
                     <template slot="prepend"><i style="font-size:20px" class="el-icon-s-custom"></i></template>
                  </el-input>
               </el-form-item>

               <el-form-item prop="password">
                  <el-input type="password" v-model="user.password" auto-complete="off" placeholder="请输入密码">
                     <template slot="prepend"><i style="font-size:20px" class="el-icon-key"></i></template>
                  </el-input>
               </el-form-item>
               
               <el-form-item prop="rolename">
                  <el-select v-model="user.rolename" placeholder="请选择角色" auto-complete="off" class="sel">
                     <el-option label="学生" value="学生"></el-option>
                     <el-option label="教师" value="教师"></el-option>
                  </el-select>

               </el-form-item>
               <el-form-item>
                  <el-button style="width:100%;" type="success" @click="register">注册</el-button>
               </el-form-item>
               <el-form-item class="flex">
                  <el-link type="info" :underline="false" @click="LoginchangeMsg(), clearuser()">
                     ← 返回
                  </el-link>
               </el-form-item>
            </el-form>
         </div>
      </el-card>
   </div>
</template>

<script>
import request from "@/utils/request";
// import qs from 'qs'



export default {
   data() {
      return {
         //表单验证
         isRegister: false,
         user: {
            userid: '',
            username: '',
            password: '',
            rolename: ''
         },
         loginRules: {
            username: [
               { validator: this.checkUsername, trigger: 'blur' },


            ],
            password: [
               { validator: this.checkPassword, trigger: 'blur' },

            ]
         }
      }
   },
   methods: {
      //   //登录api调用
      //   handleLogin() {
      //    request.post("/user/loging", this.user.value).then(res=> {
      //       console.log(this.user.value)
      //       if (res.data.code == '0') {
      //          this.$router.push('/index')
      //          this.$message({
      //             message: '登录成功',
      //             type: 'success'
      //          })
      //       } else {
      //          this.$message({
      //             message: res.data.message,
      //             type: 'error'
      //          });
      //       }
      //    }).catch(error => {
      //       console.error("登录时发生错误:", error);
      //       this.$message({
      //          message: '登录时发生错误，请重试',
      //          type: 'error'
      //       });
      //    });
      // },


      //登录点击事件
      async handleLogin() {
         //把实体数据序列化，不是以json数据形式传送到后台，以form-data
         try {
            // let logindata = qs.stringify({
            //    username: this.user.username,
            //    password: this.user.password,
            //    rolename: this.user.rolename
            // })
            // 假设this.user包含用户名和密码
            // console.log(logindata)
            // const res = await request.post('/user/loging', logindata);
            const res = await request.post('/user/loging',this.user);
            console.log(res.data.code)
            console.log(res.data.message)
            console.log(res.data)
            // 假设后端返回的状态码为200表示成功，且数据结构包含code和message
            if (res.data.code == '0') {
               localStorage.setItem("user",JSON.stringify(res.data));//存储用户信息到浏览器
               this.$router.push('/'); // 跳转到主页或其他受保护的页面
               this.$message({
                  message: '登录成功',
                  type: 'success'
               });
            } else {
               // 登录失败，显示错误信息
               this.$message({
                  message: res.data.message,
                  type: 'error'
               });
            }
         } catch (error) {
            // 网络错误或其他异常
            console.error('登录时发生错误:', error);
            this.$message({
               message: '登录时发生错误，请重试',
               type: 'error'
            });
         }
      },

      //注册接口实现
      register() {
         request.post("/user/toregister", this.user).then(res => {
            if (res.data.code == '0') {
               this.$message({
                  message: '注册成功',
                  type: 'success'
               })
               this.isRegister=false
            } else {
               this.$message({
                  message: '用户名被占用',
                  type: 'error'
               });
            }
         }).catch(error => {
            console.error("注册时发生错误:", error);
            this.$message({
               message: '注册时发生错误，请重试',
               type: 'error'
            });
         });
      },

      //校验用户名
      checkUsername(rule, value, callback) {
         if (!value) {
            // 明确调用callback以处理错误情况
            callback(new Error('用户名不能为空'));
         } else {
            // 直接进行长度验证，无需setTimeout
            if (value.length < 5 || value.length > 15) {
               callback(new Error('用户名长度应为5~15个字符'));
            } else {
               // 如果验证通过，也需要调用callback，表示验证完成且无错误
               callback();
            }
         }
      },
      //校验密码
      checkPassword(rule, value, callback) {
         if (!value) {
            // 明确调用callback以处理错误情况
            callback(new Error('密码不能为空'));
         } else {
            // 直接进行长度验证，无需setTimeout
            if (value.length < 5 || value.length > 15) {
               callback(new Error('密码长度应为5~15个字符'));
            } else {
               // 如果验证通过，也需要调用callback，表示验证完成且无错误
               callback();
            }
         }
      },
      //注册表单切换提醒
      RegisterchangeMsg() {
         this.isRegister= true
         this.$message({
            message: '注册切换成功',
            type: 'success'
         })
      },
      //返回登陆表单切换提醒信息
      LoginchangeMsg() {
         this.isRegister= false
         this.$message({
            message: '返回登陆成功',
            type: 'success'
         })
      },
      //清理切换表单的残留数据
      clearuser() {
         this.user = {
            username: '',
            password: '',
            rolename: ''
         }

      }

   }
}
</script>

<style lang="less" scoped>
.login-page {
   /* background:whitesmoke; */
   background: url('@/assets/backgroud.jpg') no-repeat center / cover;
   ;
   height: 100vh;
   display: flex;
   justify-content: center;
   align-items: center;
}

.clearfix {

   width: 100%;
   height: 60px;
   background: url('@/assets/jiaowu.png') no-repeat center / cover;
   ;
   /* background: red; */

}

.login-title {
   font-size: 20px;

}
.el-input {
   width: 100%;
}

.box-card {
   width: 375px;
   background: rgb(243, 245, 243);
   opacity: 0.9; 
}

.sel {
   display: flex;

}
</style>
